<template>
	<div class="wrapper">
	  <header>
		<i class="fa fa-angle-left" @click="navigateToSettings"></i>
		<p>地址管理</p>
	  </header>
	  
	  <!-- 成功/错误提示 -->
	  <div class="toast-container" v-if="toast.show">
	    <div class="toast" :class="toast.type">
	      <i :class="toast.icon"></i>
	      <span>{{ toast.message }}</span>
	    </div>
	  </div>

	  <!-- 确认删除对话框 -->
	  <div class="confirm-dialog" v-if="confirmDialog.show">
	    <div class="confirm-overlay" @click="cancelDelete"></div>
	    <div class="confirm-content">
	      <div class="confirm-icon">
	        <i class="fa fa-exclamation-triangle"></i>
	      </div>
	      <h3>{{ confirmDialog.title }}</h3>
	      <p>{{ confirmDialog.message }}</p>
	      <div class="confirm-buttons">
	        <button class="cancel-btn" @click="cancelDelete">
	          <i class="fa fa-times"></i> 取消
	        </button>
	        <button class="confirm-btn" @click="confirmDelete">
	          <i class="fa fa-check"></i> 确定
	        </button>
	      </div>
	    </div>
	  </div>
	  
	  <div class="content-container">
	    <!-- 没有地址时显示的提示 -->
	    <div v-if="deliveryAddressArr.length === 0" class="no-address">
	      <i class="fa fa-map-marker"></i>
	      <p>您还没有添加收货地址</p>
	    </div>
	    
	    <ul class="addresslist">
		  <li v-for="item in deliveryAddressArr" :key="item.id" class="address-card">
		    <div class="addresslist-left" @click="setDeliveryAddress(item)">
			  <div class="name-phone">
			    <span class="name">{{ item.contactName }}</span>
			    <span class="gender">{{ item.contactSex == 1 ? "先生" : "女士" }}</span>
			    <span class="phone">{{ item.contactTel }}</span>
			  </div>
			  <div class="address">
			    <i class="fa fa-map-marker"></i>
			    <p>{{ item.address }}</p>
			  </div>
		    </div>
		    <div class="addresslist-right">
			  <div class="action-btn edit" @click="editUserAddress(item)">
			    <i class="fa fa-edit"></i>
			    <span>编辑</span>
			  </div>
			  <div class="action-btn delete" @click="removeUserAddress(item.id)">
			    <i class="fa fa-trash"></i>
			    <span>删除</span>
			  </div>
		    </div>
		  </li>
	    </ul>
	  </div>
	  
	  <div class="addbtn" @click="toAddUserAddress">
		<i class="fa fa-plus"></i>
		<p>新增收货地址</p>
	  </div>
	  <Footer></Footer>
	</div>
  </template>
  <script setup>
  import Footer from "../components/Footer.vue";
  import { useRouter, useRoute } from "vue-router";
  import { ref, onMounted, onActivated } from "vue";
  import { addressApi } from '@/api';
  import { setLocalStorage } from "../common.js";
  
  const router = useRouter();
  const route = useRoute();
  const user = JSON.parse(localStorage.getItem("user-info"));
  const businessId = route.query.businessId;
  const deliveryAddressArr = ref([]);
  
  // 获取当前用户的地址列表
  const listDeliveryAddresses = async () => {
    try {
      // 使用新的API接口获取地址列表
      const addresses = await addressApi.getAddressList();
      deliveryAddressArr.value = addresses || [];
      console.log('地址列表获取成功:', deliveryAddressArr.value);
    } catch (error) {
      console.error('获取地址列表失败:', error);
    }
  };
  
  // 组件挂载时获取数据
  onMounted(() => {
    console.log('UserAddress页面挂载，获取地址列表');
    listDeliveryAddresses();
  });
  
  // 页面被激活时也重新获取数据（用于页面缓存场景）
  onActivated(() => {
    console.log('UserAddress页面激活，重新获取地址列表');
    listDeliveryAddresses();
  });
  
  const setDeliveryAddress = (deliveryAddress) => {
	setLocalStorage(user.id, deliveryAddress);
	router.push({
	  path: "/orders",
	  query: { businessId: businessId }
	});
  };
  
  const toAddUserAddress = () => {
	router.push({
	  path: "/addUserAddress",
	  query: { businessId: businessId }
	});
  };
  
  const editUserAddress = (address) => {
    // 将地址对象序列化并传递给编辑页面
    const addressData = encodeURIComponent(JSON.stringify(address));
    router.push({
      path: "/editUserAddress",
      query: { 
        businessId: businessId, 
        daId: address.id,
        addressData: addressData 
      }
    });
  };
  
  // 提示消息
  const toast = ref({
    show: false,
    message: '',
    type: 'success',
    icon: 'fa fa-check-circle'
  });

  // 显示提示消息
  const showToast = (message, type = 'success') => {
    toast.value.show = true;
    toast.value.message = message;
    toast.value.type = type;
    toast.value.icon = type === 'success' ? 'fa fa-check-circle' : 'fa fa-exclamation-circle';
    
    // 3秒后自动关闭
    setTimeout(() => {
      toast.value.show = false;
    }, 3000);
  };
  
  // 确认对话框
  const confirmDialog = ref({
    show: false,
    title: '',
    message: '',
    itemId: null
  });

  // 显示确认对话框
  const showConfirmDialog = (id, title = '确认删除', message = '确定要删除此送货地址吗？') => {
    confirmDialog.value.show = true;
    confirmDialog.value.title = title;
    confirmDialog.value.message = message;
    confirmDialog.value.itemId = id;
  };

  // 取消删除
  const cancelDelete = () => {
    confirmDialog.value.show = false;
  };

  // 确认删除
  const confirmDelete = async () => {
    if (confirmDialog.value.itemId) {
      try {
        await addressApi.removeAddress(confirmDialog.value.itemId);
        showToast("地址删除成功");
        listDeliveryAddresses();
      } catch (error) {
        console.error('删除地址失败:', error);
        showToast("地址删除失败：" + (error.message || "未知错误"), "error");
      }
      confirmDialog.value.show = false;
    }
  };
  
  const removeUserAddress = (addressId) => {
    showConfirmDialog(addressId);
  };

  const navigateToSettings = () => {
    router.push({ path: "/settings" });
  };
  </script>
  <style scoped>
/****************** 总容器 ******************/
.wrapper {
  width: 100%;
  height: 100%;
  background-color: #f5f5f5;
  overflow: auto;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}

/****************** header部分 ******************/
.wrapper header {
  width: 100%;
  height: 12vw;
  background-color: #0097ff;
  color: #fff;
  font-size: 4.8vw;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
  display: flex;
  justify-content: center;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.wrapper header i {
  font-size: 6vw;
  position: absolute;
  left: 4vw;
  cursor: pointer;
  color: #fff;
  transition: transform 0.3s ease;
}

.wrapper header i:hover {
  transform: translateX(-2px);
}

/* 内容容器 */
.content-container {
  width: 100%;
  padding: 16vw 4vw 14vw;
  box-sizing: border-box;
}

/* 空地址状态 */
.no-address {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 10vw 0;
}

.no-address i {
  font-size: 20vw;
  color: #cccccc;
  margin-bottom: 3vw;
}

.no-address p {
  font-size: 4vw;
  color: #999;
}

/****************** 地址列表部分 ******************/
.wrapper .addresslist {
  width: 100%;
}

.address-card {
  width: 100%;
  background-color: #fff;
  border-radius: 12px;
  padding: 3vw 4vw;
  box-sizing: border-box;
  margin-bottom: 3vw;
  display: flex;
  flex-direction: column;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: transform 0.2s, box-shadow 0.2s;
}

.address-card:active {
  transform: scale(0.98);
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.addresslist-left {
  width: 100%;
  padding: 2vw 0;
}

.name-phone {
  display: flex;
  align-items: center;
  margin-bottom: 2vw;
}

.name {
  font-size: 4.2vw;
  font-weight: 600;
  color: #333;
}

.gender {
  font-size: 3.6vw;
  color: #666;
  margin: 0 2vw;
}

.phone {
  font-size: 3.8vw;
  color: #333;
}

.address {
  display: flex;
  align-items: flex-start;
}

.address i {
  font-size: 4vw;
  color: #0097ff;
  margin-right: 2vw;
  margin-top: 0.5vw;
}

.address p {
  font-size: 3.6vw;
  color: #666;
  line-height: 1.4;
  flex: 1;
}

.addresslist-right {
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #f0f0f0;
  padding-top: 2vw;
  margin-top: 2vw;
}

.action-btn {
  display: flex;
  align-items: center;
  padding: 2vw 3vw;
  border-radius: 4px;
  cursor: pointer;
}

.action-btn i {
  font-size: 3.8vw;
  margin-right: 1vw;
}

.action-btn span {
  font-size: 3.6vw;
}

.edit {
  color: #0097ff;
  margin-right: 3vw;
}

.delete {
  color: #ff4d4f;
}

/****************** 添加按钮 ******************/
.wrapper .addbtn {
  width: 90%;
  height: 12vw;
  background-color: #0097ff;
  border-radius: 8px;
  margin: 0 auto;
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  box-shadow: 0 4px 12px rgba(0, 151, 255, 0.3);
  cursor: pointer;
  transition: transform 0.2s, box-shadow 0.2s;
  position: fixed;
  bottom: 16vw;
  left: 5%;
  z-index: 999;
}

.wrapper .addbtn:active {
  transform: scale(0.98);
  box-shadow: 0 2px 8px rgba(0, 151, 255, 0.2);
}

.wrapper .addbtn i {
  font-size: 5vw;
  margin-right: 2vw;
}

.wrapper .addbtn p {
  font-size: 4vw;
  font-weight: 500;
}

/* 提示消息样式 */
.toast-container {
  position: fixed;
  top: 20%;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  z-index: 2000;
  pointer-events: none;
}

.toast {
  padding: 3vw 6vw;
  border-radius: 8px;
  display: flex;
  align-items: center;
  font-size: 3.8vw;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  animation: fadeInOut 0.3s ease;
}

.toast.success {
  background-color: rgba(56, 202, 115, 0.95);
  color: white;
}

.toast.error {
  background-color: rgba(255, 77, 79, 0.95);
  color: white;
}

.toast i {
  font-size: 4.5vw;
  margin-right: 3vw;
}

@keyframes fadeInOut {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 确认对话框样式 */
.confirm-dialog {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2001;
}

.confirm-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
}

.confirm-content {
  width: 80%;
  background-color: white;
  border-radius: 12px;
  padding: 5vw;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
  display: flex;
  flex-direction: column;
  align-items: center;
  position: relative;
  z-index: 2002;
  animation: scaleIn 0.3s ease;
}

.confirm-icon {
  width: 15vw;
  height: 15vw;
  background-color: #fff0f0;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 4vw;
}

.confirm-icon i {
  font-size: 8vw;
  color: #ff4d4f;
}

.confirm-content h3 {
  font-size: 4.5vw;
  color: #333;
  margin-bottom: 3vw;
}

.confirm-content p {
  font-size: 3.8vw;
  color: #666;
  text-align: center;
  margin-bottom: 5vw;
}

.confirm-buttons {
  width: 100%;
  display: flex;
  justify-content: space-between;
}

.confirm-buttons button {
  width: 48%;
  height: 11vw;
  border-radius: 6px;
  font-size: 4vw;
  display: flex;
  justify-content: center;
  align-items: center;
  border: none;
  cursor: pointer;
  transition: transform 0.2s;
}

.confirm-buttons button:active {
  transform: scale(0.98);
}

.confirm-buttons button i {
  margin-right: 2vw;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background-color: #ff4d4f;
  color: white;
}

@keyframes scaleIn {
  from {
    transform: scale(0.8);
    opacity: 0;
  }
  to {
    transform: scale(1);
    opacity: 1;
  }
}
</style>